import { type NextRequest, NextResponse } from 'next/server';

export class WeatherHandler {
    handle = async (request: NextRequest) => {
        const method = request.method.toUpperCase();

        if (method === 'GET') {
            const { searchParams } = new URL(request.url);
            const city = searchParams.get('city');

            if (!city) {
                return NextResponse.json({ error: 'City is required' }, { status: 400 });
            }

            // 1. 从环境变量中安全地获取 API 密钥
            // 这个密钥只存在于服务器，绝不会泄露到客户端
            const API_KEY = process.env.WEATHER_API_KEY;
            const REAL_API_URL = `https://api.weatherapi.com/v1/current.json?key=${API_KEY}&q=${city}`;

            try {
                // 2. Next.js 服务器发起对真实后端的请求
                const response = await fetch(REAL_API_URL, {
                    next: { revalidate: 3600 } // ✨ 缓存1小时
                });

                if (!response.ok) {
                    throw new Error('Failed to fetch weather data');
                }

                const data = await response.json();

                // 3. (可选) 裁剪数据，只返回前端需要的部分
                const simplifiedData = {
                    location: data.location.name,
                    temp_c: data.current.temp_c,
                    condition: data.current.condition.text,
                };

                console.error('Weather API ok:', simplifiedData);
                // 4. 将处理好的数据返回给前端
                return NextResponse.json(simplifiedData);

            } catch (error) {
                console.error('Weather API error:', error);
                return NextResponse.json({ error: 'Failed to fetch weather data' }, { status: 500 });
            }
        }

        return NextResponse.json({ error: 'Method not allowed' }, { status: 405 });
    };
}
